/*
Copyright  2018 Blockchain Technology and Application Joint Lab, Fintech Research Center of ISCAS.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */
import { HTTP } from 'meteor/http'
import {createTransaction} from '../api/repchainTransactionHelper';
import settings from '../../setting.js';

settings = new settings();

//根据API获取RepChian块的高度
getBlockByHeight = function (height, cb) {
    let purl = 'http://' + settings.websocket_host + ':' + settings.websocket_port + '/block/' + height;
        HTTP.call('GET', purl, {
        headers: {
            'Content-Type':'application/json',
            'Access-Control-Allow-Origin': '*',
        }
    }, (error, result) => {
        //服务的逻辑错误仍然以200返回，但是data.err不为空
        let err = error || result.data.err;
        if (!err) {
            cb(null, result.content);
        }else{
            if(err.toString() == 'Error: network')
                cb({error:error.toString(), message:"连接repchain出错，查看日志获取更多信息"}, null)
            else
                cb({error:error,message:result.data.err}, null)
        }
    });
};
//根据API通过hash获取块
getBlockByHash = function (hash, cb) {
    let purl = 'http://' + settings.websocket_host + ':' + settings.websocket_port + '/block/hash/' + hash;
    HTTP.call('GET', purl, {
        headers: {
            'Content-Type':'application/json',
            'Access-Control-Allow-Origin': '*',
        }
    }, (error, result) => {
        //服务的逻辑错误仍然以200返回，但是data.err不为空
        let err = error || result.data.err;
        if (!err) {
            cb(null, result.content);
        }else{
            if(err.toString() == 'Error: network')
                cb({error:error.toString(), message:"连接repchain出错，查看日志获取更多信息"}, null)
            else
                cb({error:error,message:result.data.err}, null)
        }
    });
}
//根据API看当前值是否已注册过
exports.verifyHash = function(hash, cb){
    let postContent = {
        hash: hash,
        cid: settings.chainCodeId_name
    }
    let purl = 'http://' + settings.websocket_host + ':' + settings.websocket_port + '/hash/verifyHash';
    HTTP.call('POST', purl, {
        headers: {
            'Content-Type':'application/json',
            'Access-Control-Allow-Origin': '*',
        },
        data: postContent
    }, (error, result) => {
        //服务的逻辑错误仍然以200返回，但是data.err不为空
        let err = error || result.data.err;
        console.log(result)
        console.log(err)
        if (!err) {
            cb(null, result.content);
        }else{
            if(err.toString() == 'Error: network')
                cb({error:error.toString(), message:"连接repchain出错，查看日志获取更多信息"}, null)
            else
                cb({error:error,message:result.data.err}, null)
        }
    });
}

/**
 * 获取证书短地址
 * @param certificate 证书
 * @param cb callback
 */
exports.getAccountAddress = function (certificate, cb) {
    if (typeof certificate === 'string') {
        let postContent = {
            cert: certificate,
            cid: settings.chainCodeId_name,
        }
        let purl = 'http://'+settings.websocket_host
            +':'+settings.websocket_port+
            '/certAddr/getAddrByCert';
        HTTP.call('POST', purl, {
            headers: {
                'Content-Type':'application/json',
                'Access-Control-Allow-Origin': '*',
            },
            data:postContent
        }, (error, result) => {
            //服务的逻辑错误仍然以200返回，但是data.err不为空
            let err = error || result.data.err;
            console.log(result)
            if (!err) {
                cb(null, result.content);
            }else{
                if(err.toString() == 'Error: network')
                    cb({error:error.toString(), message:"连接repchain出错，查看日志获取更多信息"}, null)
                else
                    cb({error:error,message:result.data.err}, null)
            }
        });
    } else
        throw new Error('Invalid parameter \'certificate\' in function getAccountAddr');
}

//获取RepChain当前的状态信息
exports.getChaininfo = function(cb){
    let purl = 'http://' + settings.websocket_host + ':' + settings.websocket_port + '/chaininfo';
    HTTP.call('GET', purl, {
        headers: {
            'Content-Type':'application/json',
            'Access-Control-Allow-Origin': '*',
        }
    }, (error, result) => {
        //服务的逻辑错误仍然以200返回，但是data.err不为空
        let err = error || result.data.err;
        if (!err) {
            cb(null, result.content);
        }else{
            if(err.toString().search('Error: connect ECONNREFUSED')>=0)
                cb({error:error.toString(), message:"连接repchain出错，查看日志获取更多信息"}, null)
            else
                cb({error:error,message:result.data.err}, null)
        }
    });
}

//获取块 字符串或者数字形式
exports.getBlock = function (id, cb) {
    if (typeof id === 'string') {
        getBlockByHash(id, cb);
    }
    else if (typeof id === 'number') {
        getBlockByHeight(id, cb);
    }
    else {
        throw new Error('Invalid parameter \'id\' in function getBlock');
    }
}

//根据交易号获取交易信息
exports.getTransaction = function (txid, cb) {
    let purl = 'http://' + settings.websocket_host + ':' + settings.websocket_port + '/transaction/' + txid;
    HTTP.call('GET', purl, {
        headers: {
            'Content-Type':'application/json',
            'Access-Control-Allow-Origin': '*',
        }
    }, (error, result) => {
        //服务的逻辑错误仍然以200返回，但是data.err不为空
        let err = error || result.data.err;
        if (!err) {
            cb(null, result.content);
        }else{
            if(err.toString() == 'Error: network')
                cb({error:error.toString(), message:"连接repchain出错，查看日志获取更多信息"}, null)
            else
                cb({error:error,message:result.data.err}, null)
        }
    });
}

/**
 * 注销用户
 * @param user_account_addr
 * @param prv_key_pem
 * @account_address account address
 * @param cb
 */
exports.destroyUser = function (user_account_addr, prv_key_pem, account_address, cb) {
    let chainCodeFunc = "destroyCert";
    let chainCodeArgs = ['\"' + user_account_addr + '\"']
    createTransaction(chainCodeFunc, chainCodeArgs, prv_key_pem, account_address, (bytesHexStr, txid) => {
        let purl = 'http://'+settings.websocket_host
            +':'+settings.websocket_port+
            '/transaction/postTranByString';
        HTTP.call('POST', purl, {
            headers: {
                'Content-Type':'application/json',
                'Access-Control-Allow-Origin': '*',
            },
            data: bytesHexStr
        }, (error, result) => {
            //服务的逻辑错误仍然以200返回，但是data.err不为空
            let err = error || result.data.err;
            if (!err) {
                cb(null, result.content, txid);
            }else{
                if(err.toString() == 'Error: network')
                    cb({error:error.toString(), message:"连接repchain出错，查看日志获取更多信息"}, null)
                else
                    cb({error:error,message:result.data.err}, null)
            }
        });
    })
}

/**
 * 更新用户信息
 * @param certificate
 * @param prv_key_pem
 * @account_address account address
 * @param cb
 */
exports.updateUserCertificate = function (certificate, prv_key_pem, account_address, cb) {
    let chainCodeFunc = "replaceCert";
    let chainCodeArgs = ['{\"cert\":\"' + certificate +'\",\"addr\":\"' + account_address +'\"}']
    createTransaction(chainCodeFunc, chainCodeArgs, prv_key_pem, account_address, (bytesHexStr, txid) => {
        let purl = 'http://'+settings.websocket_host
            +':'+settings.websocket_port+
            '/transaction/postTranByString';
        HTTP.call('POST', purl, {
            headers: {
                'Content-Type':'application/json',
                'Access-Control-Allow-Origin': '*',
            },
            data: bytesHexStr
        }, (error, result) => {
            //服务的逻辑错误仍然以200返回，但是data.err不为空
            let err = error || result.data.err;
            if (!err) {
                cb(null, result.content, txid);
            }else{
                if(err.toString() == 'Error: network')
                    cb({error:error.toString(), message:"连接repchain出错，查看日志获取更多信息"}, null)
                else
                    cb({error:error,message:result.data.err}, null)
            }
        });
    })
}

/**
 * 注册用户证书
 * @param certificate
 * @param desc
 * @param prv_key_pem
 * @account_address account address
 * @param cb
 */
exports.registerUserCertificate = function (certificate, desc, prv_key_pem, account_address, cb) {
    let chainCodeFunc = "signup";
    let chainCodeArgs = ['{\"' + certificate + '\":\"' + desc +'\"}']
    createTransaction(chainCodeFunc, chainCodeArgs, prv_key_pem, account_address, (bytesHexStr, txid) => {
    //c4w 4.11
        let purl = 'http://'+settings.websocket_host
            +':'+settings.websocket_port+
            '/transaction/postTranByString';
        HTTP.call('POST', purl, {
            headers: {
                'Content-Type':'application/json',
                'Access-Control-Allow-Origin': '*',
            },
          data: bytesHexStr
        }, (error, result) => {
            //服务的逻辑错误仍然以200返回，但是data.err不为空
            let err = error || result.data.err;
            if (!err) {
                cb(null, result.content, txid);
            }else{
                if(err.toString() == 'Error: network')
                    cb({error:error.toString(), message:"连接repchain出错，查看日志获取更多信息"}, null)
                else
                    cb({error:error,message:result.data.err}, null)
            }
        });
    })
},
//注册版权信息
exports.registerCopyright = function (hash, val, prv_key_pem, account_address, cb) {
    let chainCodeFunc = "put_proof";
    let chainCodeArgs = ['{\"' + hash + '\":\"' + val +'\"}']
    createTransaction(chainCodeFunc, chainCodeArgs, prv_key_pem, account_address, (t_bytes_hex_str, txid) => {
        let purl = 'http://'+settings.websocket_host
            +':'+settings.websocket_port+
            '/transaction/postTranByString';
        HTTP.call('POST', purl, {
            headers: {
                'Content-Type':'application/json',
                'Access-Control-Allow-Origin': '*',
            },
            data: t_bytes_hex_str
        }, (error, result) => {
            //服务的逻辑错误仍然以200返回，但是data.err不为空
            let err = error || result.data.err;
            if (!err) {
                cb(null, result.content, txid);
            }else{
                if(err.toString() == 'Error: network')
                    cb({error:error.toString(), message:"连接repchain出错，查看日志获取更多信息"}, null)
                else
                    cb({error:error,message:result.data.err}, null)
            }
        });
        let data = {
            stype: 2,
            idPath: 'path',
            idName: '1add8db6a80ea8c2da96a766918a245e7e51c642da57c90277be3ad24497c75e',
            iptFunc: 'put_proof(\'' + hash + '\',\'' + val + '\');',
            iptArgs: [],
            timeout: 0,
            secureContext: 'string',
            code: 'string',
        };
    })
}